package com.cwnu.sw.cys.core.common.event.listener;

import com.cwnu.sw.cys.core.common.domain.enums.IdempotentEnum;
import com.cwnu.sw.cys.core.common.event.UserRegisterEvent;
import com.cwnu.sw.cys.core.user.dao.UserDao;
import com.cwnu.sw.cys.core.user.domain.entity.User;
import com.cwnu.sw.cys.core.user.domain.enums.ItemEnum;
import com.cwnu.sw.cys.core.user.service.UserBackpackService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.transaction.event.TransactionPhase;
import org.springframework.transaction.event.TransactionalEventListener;

/**
 * 用户注册事件监听器
 *
 * @author jisam
 * @version 1.0
 * @contact "jisamchan@outlook.com"
 * @date 29/03/2025
 */
@Component
@Slf4j
public class UserRegisterEventListener {

    @Autowired
    private UserBackpackService userBackpackService;

    @Autowired
    private UserDao userDao;

    /**
     * 处理用户注册事件，发放改名卡
     *
     * @param event 用户注册事件
     */
    @Async
    @TransactionalEventListener(classes = UserRegisterEvent.class, phase = TransactionPhase.AFTER_COMMIT)
    public void handleUserRegisterEvent(UserRegisterEvent event) {
        User user = event.getUser();
        userBackpackService.acquireItem(user.getId(), ItemEnum.MODIFY_NAME_CARD.getId(), IdempotentEnum.UID, user.getId().toString());
        log.info("用户注册事件监听器 发放改名卡");
    }

    /**
     * 处理用户注册事件，发放头衔
     *
     * @param event 用户注册事件
     */
    @TransactionalEventListener(classes = UserRegisterEvent.class, phase = TransactionPhase.AFTER_COMMIT)
    public void sendBadges(UserRegisterEvent event) {
        User user = event.getUser();
        int cnt = userDao.count();
        if (cnt < 10) {
            userBackpackService.acquireItem(user.getId(), ItemEnum.REG_TOP10_BADGE.getId(), IdempotentEnum.UID, user.getId().toString());
        } else if (cnt < 100) {
            userBackpackService.acquireItem(user.getId(), ItemEnum.REG_TOP100_BADGE.getId(), IdempotentEnum.UID, user.getId().toString());
        }
        log.info("用户注册事件监听器 发放头衔");
    }
}
